package hotgammon.domain;

public class MoveAlphamon implements Move{
    private Board board;
    private Game game;
    
    public MoveAlphamon(Board board) {
        this.board = board;
    }
    
    public void setGame(Game game) {
        this.game = game;
    }
    
    /** Move one checker from one location to another.
     * @param from the location to move the stone from
     * @param to the location to move the stone to
     * @return false if the indicated move is illegal
     */
    public boolean move(Location from, Location to) {
        int length = Location.distance(from, to);
        int absLength = Math.abs(length);
        
        if(to == Location.R_BEAR_OFF || to == Location.B_BEAR_OFF || to == Location.R_BAR || to == Location.B_BAR) return false;
        
        boolean allowed = false;
        for (int n : game.getDice().getValuesLeft()) {
            if (absLength==n) allowed=true;
        }
        if (!allowed) return false;
        
        if(board.getColor(from) != game.getPlayerInTurn()) return false;
        if(board.getColor(to) != game.getPlayerInTurn() && board.getColor(to) != Color.NONE) return false;
        
        if(game.getPlayerInTurn() == Color.RED && length > 0) return false;
        if(game.getPlayerInTurn() == Color.BLACK && length < 0) return false;
        
        boolean hasDeleted = false;
        for (int n = game.getDice().getValuesLeft().length-1; n>=0 && !hasDeleted; n--) {
            if (game.getDice().getValuesLeft()[n]==absLength) {
                game.getDice().getValuesLeft()[n] = 0;
                hasDeleted=true;
            }
        }
        if (!hasDeleted) return false;

        board.move(from, to);

        if(game.getDice().getNumberOfMovesLeft() == 0) {
            game.nextTurn();
        }
        
        return true;
    }
}
